﻿Imports System.Web
Imports System.Web.Configuration
Imports System.Configuration


Public Class Crypto

    Shared Sub New()

        Dim dkey As String = System.Web.Configuration.WebConfigurationManager.AppSettings("MobileKey")
        Dim al As String = System.Web.Configuration.WebConfigurationManager.AppSettings("MobileEncryption")
        key = System.Text.Encoding.Default.GetBytes(dkey)

        Select Case al
            Case "RC2"
                al = EncryptionAlgorithm.Rc2
            Case "DES"
                al = EncryptionAlgorithm.Des
            Case "3DES"
                al = EncryptionAlgorithm.TripleDes
            Case "AES"
                al = EncryptionAlgorithm.Rijndael
            Case Else
        End Select

    End Sub
    Private Shared key As Byte()
    Private Shared algo As EncryptionAlgorithm = EncryptionAlgorithm.TripleDes
    Private Shared iv As Byte()

    Public Shared Function UserInfoToAuthToken(ByVal UserInfo As DotNetNuke.Entities.Users.UserInfo) As String
        Dim enc As New Encryptor(algo)

        If Not (iv Is Nothing) Then enc.IV = iv


        Dim payload() As Byte = System.Text.Encoding.UTF8.GetBytes(String.Format("{0}|{1}|{2}", UserInfo.UserID.ToString(), UserInfo.PortalID.ToString(), New String("0", 20)))
        Dim data() As Byte = enc.Encrypt(payload, key)
        If (iv Is Nothing) Then iv = enc.IV

        Return Convert.ToBase64String(data)

    End Function

    Public Shared Function AuthTokenToUserInfo(ByVal AuthToken As String) As DotNetNuke.Entities.Users.UserInfo
        Dim userInfo As DotNetNuke.Entities.Users.UserInfo = Nothing
        Dim dec As New Decryptor(algo)
        If Not (iv Is Nothing) Then dec.IV = iv


        Dim payload() As Byte = Convert.FromBase64String(AuthToken)
        Dim data() As Byte = dec.Decrypt(payload, key)

        Dim both As String() = System.Text.Encoding.UTF8.GetString(data).Split("|")

        Dim UserId As String = both(0)
        Dim PortalID As String = both(1)
        Dim UID As Integer = -1
        Dim PID As Integer = -1
        If (Integer.TryParse(UserId, UID) AndAlso Integer.TryParse(PortalID, PID)) Then userInfo = DotNetNuke.Entities.Users.UserController.GetUserById(PID, UID)
        If (userInfo Is Nothing) Then Throw New Exception("Could not resolve your account from your Authentication Token")
        Return userInfo
    End Function

End Class
